package com.fxwater.websocket.service;

import java.io.IOException;
import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;


import com.fxwater.websocket.util.OneThread;
import com.fxwater.websocket.util.SpringBeanFinder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@ServerEndpoint("/websocket")
@Component
public class WebSocketServer {
    private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    private final String SCENEID_KEY = "sceneId:";


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        if(redisTemplate==null){
            redisTemplate = SpringBeanFinder.findBean("stringRedisTemplate");
        }
        this.session = session;
        String sessionId = this.session.getId();
        if(redisTemplate.hasKey(sessionId)){
            redisTemplate.delete(sessionId);
        }
        //加入set中
        webSocketSet.add(this);
        //在线数加1
        addOnlineCount();
        log.info("有新连接加入！当前在线人数为{}，新加入人员sessionId:{}" , getOnlineCount(),sessionId);
        try {
            sendMessage("OK");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }
    //	//连接打开时执行
    //	@OnOpen
    //	public void onOpen(@PathParam("user") String user, Session session) {
    //		currentUser = user;
    //		System.out.println("Connected ... " + session.getId());
    //	}

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        String sessionId = this.session.getId();
        if(redisTemplate.hasKey(sessionId)){
            redisTemplate.delete(sessionId);
        }
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("有一连接关闭！当前在线人数为{},离开人员sessionId:{}" , getOnlineCount(),sessionId);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端<{}>的消息:{}" ,session.getId(),message);
        if(message.startsWith(SCENEID_KEY)){
            String sceneId = message.replace(SCENEID_KEY,"").trim();
            String sessionId = session.getId();
            if(!redisTemplate.hasKey(sessionId)){
                redisTemplate.opsForValue().set(sessionId,sceneId);
                OneThread thread = new OneThread(session,redisTemplate);
                thread.start();
            } else {
                redisTemplate.opsForValue().set(sessionId,sceneId);
            }

        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        String sessionId = session.getId();
        redisTemplate.delete(sessionId);
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
        log.info("向<{}>发送回调确认信息：{}",this.session.getId(),message);
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) {
        log.info(message);
        for (WebSocketServer item : webSocketSet) {
            try {
                log.info("向<{}>发送回调确认信息：{}",item.session.getId(),message);
                item.sendMessage(message);
            } catch (IOException ignored) {
            }
        }
    }

    private static synchronized int getOnlineCount() {
        return onlineCount;
    }

    private static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    private static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}
